//
//  HomeTableViewController.swift
//  weibo1990
//
//  Created by 曹晓龙 on 15/10/17.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 普通微博重用标示
let HomeTableViewCellNormalID = "HomeTableViewCellNormalID"

/// 转发微博重用ID
let HomeTableViewCellRetweetedID = "HomeTableViewCellRetweetedID"

class HomeTableViewController: VisitorTableViewController {

    /// 微博视图模型
    lazy var statusViewModel = StatusListsViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 未登录设置
        if !OauthViewModel.sharedOauthViewModel.isLogin {
            
            visitorView?.setupView(nil, title: "关注一些人，回这里看看有什么惊喜")
            
            return
        }
        
        // 加载数据
        loadHomeInfo()
        
        prepareForTableView()
        
        NSNotificationCenter.defaultCenter().addObserverForName(WBStatusPictureSelectedCellKey, object: nil, queue: nil) {[weak self] (notify) -> Void in
            guard let indexPath = notify.userInfo![WBStatusPictureSelectedIndexPathKey] as? NSIndexPath else {
                return
            }
            guard let urls:[NSURL] = notify.userInfo![WBStatusPictureSelectedURLsKey] as? [NSURL]! else {
                return
            }
            
            guard let cell = notify.object as? CXLTransitionPresentedDelegate else{
                return
            }
            
            let vc = CXLPhotoBrowserViewController(indexPath: indexPath, urls: urls)
            
            
            // 设置转场动画为自定义
            vc.modalPresentationStyle = UIModalPresentationStyle.Custom
            
            vc.transitioningDelegate = self?.transitionAnimator
            
            self?.transitionAnimator.setTransitonAnimatorDelegate(cell, indexPath: indexPath, dismissDelegate: vc)
            
            self?.presentViewController(vc, animated: true, completion: nil)
        }
        
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    ///  设置tableView
    private func prepareForTableView(){
        // 注册可充用Cell
        tableView.registerClass(CXLStatusRetweetCell.self, forCellReuseIdentifier: HomeTableViewCellRetweetedID)
        tableView.registerClass(CXLStatusNormalCell.self, forCellReuseIdentifier: HomeTableViewCellNormalID)
        
        // 取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        // 设置预估高度
        tableView.estimatedRowHeight = 500
        
        // 设置下拉刷新控键
        refreshControl = CXLRefreshControl()
        
        refreshControl?.tintColor = UIColor.redColor()
        
        refreshControl?.addTarget(self, action: "loadHomeInfo", forControlEvents: UIControlEvents.ValueChanged)
        
        // 上拉刷新
        
        tableView.tableFooterView = pullMoreView
    }
    
    //MARK:- 懒加载
    /// 底部菊花提示视图
    private lazy var pullMoreView:UIActivityIndicatorView = {
        
        let pm = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        pm.tintColor = UIColor.lightGrayColor()
        
        return pm
    }()
    
    /// 自定义转场动画属性
    private lazy var transitionAnimator:CXLTransitionAnimator = CXLTransitionAnimator()
    
    /// 下拉提示label
    private lazy var tipLabel:UILabel = {
       
        let label = UILabel(titleText: "", textFont: 18, color: UIColor.blueColor())
        
        label.backgroundColor = UIColor.orangeColor()
        
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
        
    }()
}

// MARK: - 代理和数据源方法
extension HomeTableViewController {
    // MARK: - 数据源方法
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusViewModel.statusListView.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let svm = statusViewModel.statusListView[indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(svm.reuseCellID, forIndexPath: indexPath) as! StatusCell
        
        cell.statusViewModel = svm
        
        ///  最后一条微博时加载更多数据
        if indexPath.row == statusViewModel.statusListView.count - 1 && !pullMoreView.isAnimating() {
            
            pullMoreView.startAnimating()
            
            loadHomeInfo()
        }
        
        cell.lblDelegate = self
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    
        return statusViewModel.statusListView[indexPath.row].cellRowHeight
        
    }
}

// MARK: - StatusCellLabelDelegaet
extension HomeTableViewController: StatusCellLabelDelegaet{
    
    func labelLinkClick(url: NSURL) {
                
        let vc = CXLHomeWebViewController(url: url)
        
        vc.hidesBottomBarWhenPushed = true
        
        navigationController?.pushViewController(vc, animated: true)
        
    }
}

// MARK: - 加载数据相关方法
extension HomeTableViewController {
    
    ///  加载首页微博数据
    func loadHomeInfo(){
        
        refreshControl?.beginRefreshing()
        
        statusViewModel.loadHomeInfo(ispullMoreData: pullMoreView.isAnimating()) { (isSuccessed) -> () in
            
            self.refreshControl?.endRefreshing()
            self.pullMoreView.stopAnimating()
            
            if !isSuccessed {
                
                SVProgressHUD.showInfoWithStatus("网络不给力")
                
                print("加载出错")
                
                return
            }
            
            self.refreshTipLbl()
            
            self.tableView.reloadData()
        }
    }
    
    ///  下拉刷新提示
    private func refreshTipLbl(){
        
        guard let newStatusCount = statusViewModel.newStatusCount else{
            return
        }
        
        let text = newStatusCount == 0 ? "没有新数据" : "刷新到了\(newStatusCount)条数据"
        
        tipLabel.text = text
        
        let height:CGFloat = 44
        
        let rect = CGRect(x: 0, y: height * -2, width: view.bounds.width, height: 44)
        
        tipLabel.frame = rect
        
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            
            let rect = CGRect(x: 0, y: height, width: self.view.bounds.width, height: 44)
            
            self.tipLabel.frame = rect
            }) {  void in
                
                UIView.animateWithDuration(1.0, animations: { () -> Void in
                    
                    self.tipLabel.frame = rect
                })
        }
    }
}